package com.syni.mdd.sjb.common.component.utils.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebUtils extends org.springframework.web.util.WebUtils {

	@SuppressWarnings("unchecked")
	public static <V> V getParamsInMap(Map<String, Object> map, String key, Class<V> clazz) {
		if (map != null) {
			Object o = map.get(key);
			if (clazz.isInstance(o)) {
				return (V) o;
			}
		}
		return null;
	}

	public static Map<String, Object> getParamsMap(HttpServletRequest request) {
		Map<String, String[]> oMap = request.getParameterMap();
		Map<String, Object> result = new HashMap<>();
		for (String paramName : oMap.keySet()) {
			if (oMap.get(paramName) != null && oMap.get(paramName).length > 0) {
				result.put(paramName, oMap.get(paramName)[0]);
			}
		}
		return result;
	}


	public static String getParamsInMap(Map<String, String> map, String key) {
		if (map != null) {
			return map.get(key);
		}
		return null;
	}

	public static boolean checkParamsIsNull(Object... objs) {
		for (Object obj : objs) {
			if (obj == null) {
				return true;
			}
			if (obj instanceof String) {
				if (StringUtils.isBlank(obj.toString())) {
					return true;
				}
			}
			if (obj instanceof Collection) {
				if (CollectionUtils.isEmpty((Collection<?>) obj)) {
					return true;
				}
			}
		}
		return false;
	}

	public static void bubbleSort(int[] arr) {
		int temp;//定义一个临时变量
		for(int i=0;i<arr.length-1;i++){//冒泡趟数
			for(int j=0;j<arr.length-i-1;j++){
				if(arr[j+1]<arr[j]){
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}

	public static String MD5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(s.getBytes("utf-8"));
			return toHex(bytes);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String toHex(byte[] bytes) {

		final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
		StringBuilder ret = new StringBuilder(bytes.length * 2);
		for (int i=0; i<bytes.length; i++) {
			ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
			ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		return ret.toString();
	}

	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	/**
	 * @Description 如果两个有值就取交集，如果第一个集合为空，则取第二个
	 * @Param Set（第一个set集合）
 	 * @Param Set
	 * @return: Set
	 * @Author: cfx
	 * @Date: 2020/2/29
	 */
	public static Set<Integer> getSpeSet(Set<Integer> ids,Set<Integer> ids2){
		if(ids2.size() > 0){
			if(ids.size() > 0){
				ids.retainAll(ids2);
			}else {
				ids.addAll(ids2);
			}
		}
		return ids;
	}

	public static Set<Integer> IntersectionBySet(Set<Integer>... ids){
		Set<Integer> resultIds = new HashSet<>();
		for(Set<Integer> integers : ids){
			if(resultIds.size() > 0){
				resultIds.retainAll(integers);
			}else {
				resultIds.addAll(integers);
			}
		}
		return resultIds;
	}

	public static String replaceEmoji(String str) {
		String patternString = "[\uD83C\uDC04-\uD83C\uDE1A]|[\uD83D\uDC66-\uD83D\uDC69]|[\uD83D\uDC66\uD83C\uDFFB-\uD83D\uDC69\uD83C\uDFFF]|[\uD83D\uDE45\uD83C\uDFFB-\uD83D\uDE4F\uD83C\uDFFF]|[\uD83C\uDC00-\uD83D\uDFFF]|[\uD83E\uDD10-\uD83E\uDDC0]|[\uD83D\uDE00-\uD83D\uDE4F]|[\uD83D\uDE80-\uD83D\uDEF6]";
		Pattern pattern = Pattern.compile(patternString);
		Matcher matcher = pattern.matcher(str);
		return matcher.replaceAll("");
	}

	public static String getRandomNoByTime(int length){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
		return sdf.format(new Date()) + CDNUtils.getStringRandom(length);
	}

	public static boolean isJSONStr(String str) {
		try {
			Object obj= JSON.parse(str);
			return true;
		} catch (Exception e) {
		}
		return false;
	}




	/**
	 * 验证是否是URL
	 * @param url
	 * @return
	 */
	public static boolean isHttpUrl(String url){

		// URL验证规则
		String regEx ="[a-zA-z]+://[^\\s]*";
		// 编译正则表达式
		Pattern pattern = Pattern.compile(regEx);
		// 忽略大小写的写法
		// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(url);
		// 字符串是否与正则表达式相匹配
		boolean rs = matcher.matches();
		return rs;

	}

	public static String getUUId(){
		String uuid = UUID.randomUUID().toString().replaceAll("-","");
		return uuid;
	}

	public static String handleUriParams(String uriParams){
		if(com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils.isNotBlank(uriParams)){
			String[] params = uriParams.split("&");
			JSONObject jsonObject = new JSONObject();
			if(params.length > 0){
				for(String param : params){
					String[] keyValue = param.split("=");
					jsonObject.put(keyValue[0],keyValue[1]);
				}
			}
			return JSON.toJSONString(jsonObject);
		}
		return JSON.toJSONString(new JSONObject());
	}

}
	
